<template>
  <div class="learning-goals">
    <div class="goals-header">
      <h3 class="goals-title">{{ title }}</h3>
      <button 
        v-if="showEditButton" 
        class="edit-btn"
        @click="toggleEditMode"
        :disabled="isSaving"
      >
        {{ isEditing ? '取消' : '编辑' }}
      </button>
    </div>
    
    <div class="goals-content">
      <!-- 每日目标卡片 -->
      <div class="goal-card">
        <div class="goal-icon">
          <i class="icon-daily"></i>
        </div>
        <div class="goal-info">
          <div class="goal-name">每日学习目标</div>
          <div class="goal-stats">
            <span class="current-value">{{ currentValue }}/{{ targetValue }}</span>
            <span class="goal-unit">{{ unit }}</span>
          </div>
        </div>
        
        <!-- 进度条 -->
        <div class="goal-progress">
          <div class="progress-bar-wrapper">
            <div 
              class="progress-bar"
              :style="{ 
                width: `${progressPercentage}%`,
                backgroundColor: getProgressColor()
              }"
            ></div>
          </div>
          <div class="progress-text">{{ progressPercentage }}%</div>
        </div>
        
        <!-- 编辑模式下的输入框 -->
        <div v-if="isEditing" class="goal-edit-inputs">
          <input
            type="number"
            v-model.number="tempTargetValue"
            class="goal-input"
            :placeholder="`设置${goalTypeText}`"
            :min="minimumValue"
            :max="maximumValue"
          />
          <button 
            class="save-btn"
            @click="saveGoal"
            :disabled="!canSave || isSaving"
          >
            {{ isSaving ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
      
      <!-- 周目标统计 -->
      <div class="weekly-stats" v-if="showWeeklyStats">
        <h4 class="weekly-stats-title">本周完成情况</h4>
        <div class="week-days">
          <div 
            v-for="day in weekDays"
            :key="day.date"
            class="week-day"
            :class="{ 
              'completed': day.completed,
              'current': day.isToday,
              'future': day.isFuture
            }"
          >
            <div class="day-name">{{ day.name }}</div>
            <div class="day-circle">
              <span v-if="day.completed" class="check-icon">✓</span>
              <span v-else-if="day.isToday" class="today-number">{{ day.dayNumber }}</span>
              <span v-else-if="!day.isFuture" class="day-number">{{ day.dayNumber }}</span>
            </div>
            <div v-if="day.value" class="day-value">{{ day.value }}{{ unit }}</div>
          </div>
        </div>
        <div class="weekly-summary">
          <div class="summary-item">
            <span class="summary-label">已完成天数：</span>
            <span class="summary-value">{{ completedDays }}/{{ totalWeekDays }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">本周总计：</span>
            <span class="summary-value">{{ weeklyTotal }}{{ unit }}</span>
          </div>
        </div>
      </div>
      
      <!-- 目标设置建议 -->
      <div class="goal-suggestions" v-if="showSuggestions && suggestions.length > 0">
        <h4 class="suggestions-title">推荐设置</h4>
        <div class="suggestion-list">
          <button 
            v-for="suggestion in suggestions"
            :key="suggestion.value"
            class="suggestion-btn"
            :class="{ 'active': tempTargetValue === suggestion.value }"
            @click="setSuggestion(suggestion.value)"
            :disabled="isSaving"
          >
            {{ suggestion.label }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { useProgressStore } from '@/store'
import { formatNumber } from '@/utils/formatUtils'

export default {
  name: 'LearningGoals',
  props: {
    title: {
      type: String,
      default: '学习目标'
    },
    goalType: {
      type: String,
      default: 'words',
      validator: (value) => {
        return ['words', 'time', 'phrases'].includes(value)
      }
    },
    showEditButton: {
      type: Boolean,
      default: true
    },
    showWeeklyStats: {
      type: Boolean,
      default: true
    },
    showSuggestions: {
      type: Boolean,
      default: true
    },
    minimumValue: {
      type: Number,
      default: 5
    },
    maximumValue: {
      type: Number,
      default: 200
    },
    // 以下属性如果没有传入，则从store中获取
    currentValue: {
      type: Number,
      default: null
    },
    targetValue: {
      type: Number,
      default: null
    },
    weekDays: {
      type: Array,
      default: null
    }
  },
  emits: ['goal-updated', 'goal-saved'],
  setup(props, { emit }) {
    const progressStore = useProgressStore()
    const isEditing = ref(false)
    const isSaving = ref(false)
    const tempTargetValue = ref(0)
    
    // 初始化临时目标值
    const initializeTempValue = () => {
      const target = props.targetValue !== null ? props.targetValue : progressStore.dailyGoal
      tempTargetValue.value = target || 20
    }
    
    // 获取当前值（从props或store）
    const getCurrentValue = () => {
      return props.currentValue !== null ? props.currentValue : progressStore.dailyProgress
    }
    
    // 获取目标值（从props或store）
    const getTargetValue = () => {
      return props.targetValue !== null ? props.targetValue : progressStore.dailyGoal
    }
    
    // 获取周数据（从props或store）
    const getWeekDays = () => {
      if (props.weekDays !== null) {
        return props.weekDays
      }
      
      // 生成模拟的周数据
      const days = []
      const now = new Date()
      const today = now.getDay() || 7 // 转换为1-7表示周一到周日
      
      for (let i = 0; i < 7; i++) {
        const date = new Date(now)
        date.setDate(now.getDate() - (today - 1) + i)
        const isToday = i === today - 1
        const isFuture = i > today - 1
        
        days.push({
          date: date.toISOString().split('T')[0],
          name: ['一', '二', '三', '四', '五', '六', '日'][i],
          dayNumber: date.getDate(),
          isToday,
          isFuture,
          completed: !isFuture && Math.random() > 0.3,
          value: !isFuture ? Math.floor(Math.random() * 50) + 10 : null
        })
      }
      
      return days
    }
    
    // 计算进度百分比
    const progressPercentage = computed(() => {
      const current = getCurrentValue()
      const target = getTargetValue()
      if (target === 0) return 0
      return Math.min(Math.round((current / target) * 100), 100)
    })
    
    // 获取目标类型文本
    const goalTypeText = computed(() => {
      const typeMap = {
        words: '每日单词量',
        time: '每日学习时长',
        phrases: '每日短语量'
      }
      return typeMap[props.goalType] || '每日学习目标'
    })
    
    // 获取单位
    const unit = computed(() => {
      const unitMap = {
        words: '个',
        time: '分钟',
        phrases: '个'
      }
      return unitMap[props.goalType] || ''
    })
    
    // 计算已完成天数
    const completedDays = computed(() => {
      return getWeekDays().filter(day => day.completed).length
    })
    
    // 计算本周总天数
    const totalWeekDays = computed(() => {
      return getWeekDays().filter(day => !day.isFuture).length
    })
    
    // 计算本周总计
    const weeklyTotal = computed(() => {
      return getWeekDays()
        .filter(day => !day.isFuture && day.value)
        .reduce((sum, day) => sum + day.value, 0)
    })
    
    // 获取进度颜色
    const getProgressColor = () => {
      const progress = progressPercentage.value
      if (progress >= 100) return '#52c41a'
      if (progress >= 70) return '#1890ff'
      if (progress >= 40) return '#faad14'
      return '#ff4d4f'
    }
    
    // 推荐设置
    const suggestions = computed(() => {
      const baseSuggestions = [
        { value: 10, label: '轻松模式' },
        { value: 20, label: '标准模式' },
        { value: 30, label: '进阶模式' },
        { value: 50, label: '挑战模式' }
      ]
      
      // 根据目标类型调整推荐值
      if (props.goalType === 'time') {
        return baseSuggestions.map(item => ({
          value: item.value * 5, // 转换为分钟
          label: item.label
        }))
      }
      
      return baseSuggestions
    })
    
    // 检查是否可以保存
    const canSave = computed(() => {
      return tempTargetValue.value >= props.minimumValue && 
             tempTargetValue.value <= props.maximumValue &&
             tempTargetValue.value !== getTargetValue()
    })
    
    // 切换编辑模式
    const toggleEditMode = () => {
      if (isSaving.value) return
      
      if (isEditing.value) {
        // 取消编辑，重置临时值
        initializeTempValue()
      } else {
        // 进入编辑模式，初始化临时值
        initializeTempValue()
      }
      
      isEditing.value = !isEditing.value
    }
    
    // 设置推荐值
    const setSuggestion = (value) => {
      if (isSaving.value) return
      tempTargetValue.value = value
    }
    
    // 保存目标
    const saveGoal = async () => {
      if (!canSave.value || isSaving.value) return
      
      isSaving.value = true
      try {
        // 这里可以调用API保存目标
        emit('goal-updated', tempTargetValue.value)
        emit('goal-saved', tempTargetValue.value)
        
        // 模拟网络请求延迟
        await new Promise(resolve => setTimeout(resolve, 800))
        
        isEditing.value = false
      } catch (error) {
        console.error('保存目标失败:', error)
        // 可以显示错误提示
      } finally {
        isSaving.value = false
      }
    }
    
    // 监听props变化
    watch(() => props.targetValue, () => {
      if (!isEditing.value) {
        initializeTempValue()
      }
    })
    
    // 初始化
    initializeTempValue()
    
    return {
      isEditing,
      isSaving,
      tempTargetValue,
      progressPercentage,
      goalTypeText,
      unit,
      completedDays,
      totalWeekDays,
      weeklyTotal,
      weekDays: computed(() => getWeekDays()),
      currentValue: computed(() => getCurrentValue()),
      targetValue: computed(() => getTargetValue()),
      suggestions,
      canSave,
      getProgressColor,
      toggleEditMode,
      setSuggestion,
      saveGoal,
      formatNumber
    }
  }
}
</script>

<style scoped>
.learning-goals {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 20px;
  overflow: hidden;
}

.goals-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.goals-title {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
  margin: 0;
}

.edit-btn {
  padding: 6px 16px;
  background: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  color: #595959;
  cursor: pointer;
  transition: all 0.3s ease;
}

.edit-btn:hover:not(:disabled) {
  background: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.edit-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 目标卡片 */
.goal-card {
  background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  position: relative;
  overflow: hidden;
}

.goal-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100" opacity="0.1"><path d="M0 50 C 30 30, 70 30, 100 50 C 70 70, 30 70, 0 50 Z" fill="%231890ff"/></svg>');
  background-repeat: no-repeat;
  background-position: right bottom;
  background-size: 40%;
}

.goal-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.icon-daily {
  display: inline-block;
  width: 24px;
  height: 24px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%231890ff"><path d="M19 3h-1V2c0-.55-.45-1-1-1s-1 .45-1 1v1H8V2c0-.55-.45-1-1-1s-1 .45-1 1v1H5c-1.11 0-2 .89-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.89 2-2V5c0-1.1-.89-2-2-2zm-7 14h-2v-4H8v-2h2V9h2v2h2v2h-2v4zm4-8h-2V7h2v2zm0 4h-2v-2h2v2z"/></svg>');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.goal-info {
  margin-bottom: 16px;
  max-width: 70%;
}

.goal-name {
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  margin-bottom: 8px;
}

.goal-stats {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.current-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
}

.goal-unit {
  font-size: 16px;
  color: #8c8c8c;
}

.goal-progress {
  margin-bottom: 16px;
}

.progress-bar-wrapper {
  width: 100%;
  height: 8px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 4px;
}

.progress-bar {
  height: 100%;
  transition: width 0.6s ease, background-color 0.3s ease;
  border-radius: 4px;
}

.progress-text {
  font-size: 14px;
  font-weight: 600;
  color: #595959;
  text-align: right;
}

/* 编辑模式 */
.goal-edit-inputs {
  display: flex;
  gap: 12px;
  align-items: center;
}

.goal-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.goal-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.save-btn {
  padding: 8px 20px;
  background: #1890ff;
  border: 1px solid #1890ff;
  border-radius: 6px;
  font-size: 14px;
  color: #ffffff;
  cursor: pointer;
  transition: all 0.3s ease;
}

.save-btn:hover:not(:disabled) {
  background: #40a9ff;
  border-color: #40a9ff;
}

.save-btn:disabled {
  background: #d9d9d9;
  border-color: #d9d9d9;
  color: #bfbfbf;
  cursor: not-allowed;
}

/* 周目标统计 */
.weekly-stats {
  margin-bottom: 24px;
}

.weekly-stats-title {
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  margin: 0 0 16px 0;
}

.week-days {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  gap: 8px;
}

.week-day {
  flex: 1;
  text-align: center;
  padding: 12px 8px;
  border-radius: 8px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.week-day:hover {
  background: #e6f7ff;
  border-color: #91d5ff;
}

.week-day.completed {
  background: #f6ffed;
  border-color: #b7eb8f;
}

.week-day.current {
  background: #e6f7ff;
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.week-day.future {
  opacity: 0.5;
}

.day-name {
  font-size: 12px;
  color: #8c8c8c;
  margin-bottom: 8px;
}

.day-circle {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #ffffff;
  border: 2px solid #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 4px;
  font-weight: 600;
  color: #595959;
  transition: all 0.3s ease;
}

.week-day.completed .day-circle {
  background: #52c41a;
  border-color: #52c41a;
  color: #ffffff;
}

.week-day.current .day-circle {
  background: #1890ff;
  border-color: #1890ff;
  color: #ffffff;
}

.check-icon {
  font-size: 16px;
}

.day-value {
  font-size: 12px;
  color: #8c8c8c;
  margin-top: 4px;
}

.weekly-summary {
  display: flex;
  justify-content: space-between;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-label {
  font-size: 14px;
  color: #8c8c8c;
}

.summary-value {
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

/* 目标设置建议 */
.goal-suggestions {
  background: #fafafa;
  border-radius: 8px;
  padding: 16px;
}

.suggestions-title {
  font-size: 14px;
  font-weight: 600;
  color: #262626;
  margin: 0 0 12px 0;
}

.suggestion-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  gap: 8px;
}

.suggestion-btn {
  padding: 8px 12px;
  background: #ffffff;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 13px;
  color: #595959;
  cursor: pointer;
  transition: all 0.3s ease;
}

.suggestion-btn:hover:not(:disabled) {
  border-color: #1890ff;
  color: #1890ff;
}

.suggestion-btn.active {
  background: #1890ff;
  border-color: #1890ff;
  color: #ffffff;
}

.suggestion-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .learning-goals {
    padding: 16px;
  }
  
  .goal-icon {
    width: 40px;
    height: 40px;
  }
  
  .icon-daily {
    width: 20px;
    height: 20px;
  }
  
  .goal-info {
    max-width: 60%;
  }
  
  .goal-stats {
    flex-direction: column;
    align-items: flex-start;
    gap: 2px;
  }
  
  .current-value {
    font-size: 20px;
  }
  
  .goal-edit-inputs {
    flex-direction: column;
  }
  
  .goal-input {
    width: 100%;
  }
  
  .week-days {
    flex-wrap: wrap;
  }
  
  .week-day {
    flex: 0 0 calc(33.333% - 5.33px);
  }
}

@media (max-width: 480px) {
  .goals-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .goal-card {
    padding: 16px;
  }
  
  .goal-icon {
    position: relative;
    top: auto;
    right: auto;
    margin-bottom: 16px;
  }
  
  .goal-info {
    max-width: 100%;
  }
  
  .weekly-summary {
    flex-direction: column;
    gap: 8px;
  }
  
  .suggestion-list {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>